﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace SpeechToText.STT
{
    public static class Languages
    {
        public const string Ru = "ru-Ru";
        public const string En = "en-En";
    }
    public class DecodedSpeech
    {
        public string Language { get; set; }
        public DateTime DateTime { get; set; }
        public string Text { get; set; }
        public double TrueIndex { get; set; }

        public DecodedSpeech()
        { }

        public DecodedSpeech(WavResource Wav, string Lang)
        {
            Language = Lang;
            DateTime = DateTime.Now;

            string RecognizedText = GoogleSpeechRequest(new FlacResouce(Wav), Lang);
            // "{\"status\":0,\"id\":\"cfcfbbf316e5a57547882e6f50fd7365-1\",\"hypotheses\":[{\"utterance\":\"купить велосипед\",\"confidence\":0.8882357}]}\n"

            Regex R = new Regex(@"utterance"":""([\S\s]+?)"",""confidence"":(.+?)[}]");

            Text = R.Match(RecognizedText).Groups[1].Value;

            string d = R.Match(RecognizedText).Groups[2].Value;

            if (d != "") TrueIndex = Convert.ToDouble(d.Replace('.', ','));

            else if (Text == "") TrueIndex = 1; else TrueIndex = 0;
        }

        static String GoogleSpeechRequest(FlacResouce Fl, string Lang)
        {
            WebRequest request = WebRequest.Create("https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang="+ Lang); //en-En
            request.Method = "POST";

            // Set the ContentType property of the WebRequest.
            request.ContentType = "audio/x-flac; rate=" + Fl.Parent.WaveFormat.SamplesPerSecond; //"16000";        
            request.ContentLength = Fl.ToArray().Length;

            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(Fl.ToArray(), 0, Fl.ToArray().Length);

            dataStream.Close();

            // Get the response.
            WebResponse response = request.GetResponse();

            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();

            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();

            return responseFromServer;
        }
    }
}
